/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.semi.fw;

import com.semi.util.FileLogger;
import com.semi.util.FormatException;
import com.semi.util.IPv4Util;

/**
 *
 * @author liaoyq
 */
public class UnIPMgr {
    protected  FileLogger mLogger = new FileLogger(UnIPMgr.class.getName());
    private UnCoderIP[] mData = new UnCoderIP[1000];
    public int size(){ return mData.length; }
    public UnCoderIP get(int index){ return mData[index]; }

    public void clear(){
        mLogger.info("remove all");
        for(int i=mData.length-1;i>=0;i--) mData[i] = null;
    }
    /*
    public int findBySeq(String seq){
        for(int i=0;i<mData.length;i++){
            if( mData[i]== null ) return -1;
            if( mData[i].mSeq.compareTo(seq)==0 ) return i;
        }
        return -1;
    }*/
    public boolean add(UnCoderIP coder){
       /* int k = findBySeq(coder.mSeq); 
        if( k>=0 ){
            mLogger.info("duplicate seq at "+k);
        }*/
        for(int i=0;i<mData.length;i++){
            if( mData[i]== null ){
                mData[i]=coder;
                mLogger.info("add to index="+i+", "+coder.dump());
                return true;
            }
            if( mData[i].validate() ) continue;
            mData[i] = coder;
            mLogger.info("add to index="+i+", "+coder.dump());
            return true;
        }
        return false;
    }
    public void remove(int index){
        mLogger.info("remove rule index="+index);
        if( mData[index]!=null ) mData[index].mEnable = false;
    }
    public int match(String s){
        if( s==null ) return -1;
        try{
            int ip = IPv4Util.ipToInt(s);
            for(int i=0;i<mData.length;i++){
                if( mData[i]!=null && mData[i].validate() ){
                    if( mData[i].match(ip) ) return i;
                } 
            }
        }catch( FormatException e){}
        return -1;
    }
    
}
